package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.services.SetAsEnvelopService;
import com.dragonfly.shutter.utils.KeywordFilter;

/**
 * 设置封面控制类
 * @author 黄挺
 *
 */
@Controller
@RequestMapping("/setAsEnvelop.html")
public class SetAsEnvelopController {
	@Autowired
	private SetAsEnvelopService setAsEnvelopService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpServletRequest request, HttpSession session,
			@RequestParam(value="pictureID") String pictureID,
			@RequestParam(value="ownerID") String ownerIDStr) {
		Integer userID = (Integer) session.getAttribute("userID");
		Integer albumID = (Integer) session.getAttribute("albumID");
		Message message = null;
		
		//未知的图片
		if(pictureID == null || ownerIDStr == null ){
			message = new Message("未知的图片", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		//非法的参数
		if(!KeywordFilter.isNumeric(pictureID) || !KeywordFilter.isNumeric(ownerIDStr)){
			message = new Message("非法的参数", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		//未知的相册
		if (albumID == null ) {
			message = new Message("您要把图片设为哪张相册的封面？", "操作失败", "picture.html?pictureID=" + pictureID);
			return new ModelAndView("message", "message", message);
		}
		
		Integer ownerID = Integer.parseInt(ownerIDStr);
		
		//操作权限不够
		if(userID == null || userID != ownerID){
			message = new Message("您不是这样图片的所有者，无法将该图片设为封面", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		
		try {
			setAsEnvelopService.doService(pictureID, albumID, userID, request.getRequestURL().toString());
		} catch (Exception e) {
			//不属于相册的图片
			e.printStackTrace();
			message = new Message("不属于相册的图片", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		return new ModelAndView("redirect:/picture.html?pictureID=" + pictureID);
	}
}
